package com.biostime.springdraw.modules.sd.service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.biostime.springdraw.common.config.Global;
import com.biostime.springdraw.common.utils.StringUtils;
import com.biostime.springdraw.common.wechat.BiostimeWechat;
import com.biostime.springdraw.modules.sd.dto.AwardDto;
import com.biostime.springdraw.modules.sd.dto.DistributedAwardDto;
import com.biostime.springdraw.modules.sd.dto.DrawDto;
import com.biostime.springdraw.modules.sd.entity.Award;
import com.biostime.springdraw.modules.sd.entity.Member;
import com.biostime.springdraw.modules.sd.entity.Moviecode;
import com.biostime.springdraw.modules.sd.entity.Section;
import com.biostime.springdraw.modules.sd.entity.Share;
import com.biostime.springdraw.modules.sd.entity.Shareaward;
import com.biostime.springdraw.modules.sd.entity.Sharegrid;
import com.biostime.springdraw.modules.sd.entity.Winner;
import com.biostime.springdraw.modules.sys.entity.User;

/**
 * 抽奖Service
 * @author chenweicheng
 * @version 2016-05-04
 */
@Service
@Transactional
public class DrawService {
	@Autowired
	private MemberService memberService;
	@Autowired
	private AwardService awardService;
	@Autowired
	private WinnerService winnerService;
	@Autowired
	private SectionService sectionService;
	@Autowired
	private ShareawardService shareawardService;
	@Autowired
	private SharegridService sharegridService;
	@Autowired
	private ShareService shareService;
	@Autowired
	private MoviecodeService codeService;
	
	/**日志打印**/
	public static Logger logger=Logger.getLogger("draw"); 	
	
	
	/**
	 * 主页面抽奖方法
	 * @author chenweicheng
	 * @version 2016-04-28
	 */
	@Transactional
	public DrawDto mainDraw(String openId,String fromSystem) {
		DrawDto dto = new DrawDto();
		Winner winner = new Winner();		
		
		//回收过期的电影兑换码
		codeService.recoveryMovie();	
		winnerService.recoveryIntimeAward();
		
		//当前奖品
		Award award = null;
		
		//获取微信用户信息
		Member member = memberService.getByOpenId(openId);
		if(member==null){
			dto.setMsg("无法获取用户信息");
		}
		
		//积分判断
		Map<String,String> ret = BiostimeWechat.Api.queryTimes(openId);
		if(ret==null){
			dto.setMsg("获取用户抽奖次数接口响应为空");
		}
		
		if(dto.getCheck()){
			String code = ret.get("code");
			if(code==null || !code.equals("100")){
				dto.setMsg(ret.get("desc"));
			}else{
				int drawTimes = StringUtils.toInteger(ret.get("drawTimes"));
				if(drawTimes<=0){
					dto.setMsg("您目前没有抽奖机会 玩转自助积分再来抽 ~");
				}
			}
		}
				
		if(dto.getCheck()){
			
			//判断奖品数量
			Winner winnerExm = new Winner();
			winnerExm.setMemberId(StringUtils.toInteger(member.getId()));
			winnerExm.setIsAward(1);
			
			//获取奖品列表
				List<Award> awards = awardService.findList(new Award());
				if(awards==null || awards.size()<=0){
					dto.setMsg("无法获取奖品列表");
				}
				
				//时间段奖品数量限制
				Section sectionExm = new Section();
				sectionExm.setNow(new Date());
				List<Section> sections = sectionService.findList(sectionExm);			
				boolean globalFlag = false;
				if(sections==null || sections.isEmpty()){
					dto.setMsg("无法获取阶段列表");
				}else{
					int random = randomInt(0,1001);
					double rate = sections.get(0).getGlobalRate();
					if(random > 0 && random <= rate * 1000){
						globalFlag = true;
					}
					logger.info("-------------"+"总体概率："+rate+"-------------"); 
					logger.info("-------------"+"随机数："+random+"-------------"); 
					logger.info("-------------"+"是否中奖："+globalFlag+"-------------"); 
				}
												
				if(dto.getCheck()){
									
					//判断是否中奖
					if(globalFlag){
																	
						award = randomAward(awardRange(sections));
						
						//锁住当前抽奖奖品
						boolean locked = awardService.lockAward(award);
						
						if(locked){
																						
								Section curSection = null;
								for(Section section : sections){
									if(StringUtils.toInteger(award.getId())==section.getAwardId()){
										curSection = section;
									}
								}
																				
								/**
								 * 积分抽奖前检查的是真·库存，积分≥1才能中，券≥1才能中，兑换码≥2才能中
								 * 真·库存=总数-已经中走的-已经分享出去（未过期）里未抽走的
								 * 如果抽到的是电影票，还要检查所配置的电影票够不够分发
								 */
								boolean checkStock = false;
								if(curSection != null ){
									
									DistributedAwardDto  drawAward = winnerService.getSectionDrawAwards(curSection.getCode(),award.getId(),0);
									int shareExistsAward = shareawardService.shareExitsOneAward(curSection.getCode(), award.getId());
									int awardNum = drawAward.getSum();		
									
									//如果是分享奖品,则检查真库存
									if(award.getIsShare().equals("1")){	
										
										 if(award.getAwardtype().getType().equals("moviecode")){ 
												if(award.getAmount() - awardNum - shareExistsAward >= 2){
													if(codeService.getNotUsedMoviecode() >=2 ){
														checkStock = true;
													}else{
														dto.setMsg("抽奖失败,所配置的电影票不够"); 
														return dto;
													}
												}else{
													dto.setMsg("抽奖失败,积分抽奖,兑换码≥2才能中"); 
													return dto;
												}
										}else{
											if(award.getAmount() - awardNum - shareExistsAward >= 1){
												checkStock = true;
											}else{
												dto.setMsg("抽奖失败,积分抽奖,积分,券≥1才能中"); 
												return dto;
											}
										}									
									}
									
									//如果不是分享奖品,则检查库存
									else{
										
										int awardSectionNum = 0;
										if(sections != null && !sections.isEmpty()){
											for(int i = 0;i<sections.size() ;i++){
												if(sections.get(i).getAwardId() == Integer.parseInt(award.getId())){
													awardSectionNum = sections.get(i).getAmount();
													break;
												}
											}
										}
															
										if(awardSectionNum >= awardNum){
											checkStock = true;
										}else{
											dto.setMsg("抽奖失败,库存不够"); 
											return dto;
										}
									}
								}									
																
								if(checkStock){			
									
									dto.setAward(true);
									dto.setAwardName(award.getName());
									dto.setDescription(award.getDescription()); 
									dto.setAwardtypeName(award.getAwardtype().getType()); 
							
									if(sendAward(award,openId)){
										dto.setAward(true);
										
										//如果奖品类型是电影兑换码
										if(award.getAwardtype().getType().equals("moviecode")){
											SimpleDateFormat sdf = new SimpleDateFormat("MMddhhmmssS");
											String str = sdf.format(new Date()) ;		
											winner.setShareCode(str); 											
											Moviecode code = codeService.getAndUse();
											if(code != null){
												winner.setMovieCode(code.getCode()); 
											}										
											if(member != null){
												Share share = new Share();										
												share.setCode(str);
												share.setMemberId(Integer.parseInt(member.getId()));
												shareService.save(share);
												dto.setShareId(share.getId());
											}											
										}											
										
										winner.setIsPrized(1); 
									}else{
										dto.setAward(false);
									}
									 
								}
		
						}						
					}
					
				}
						
			winner.setMemberId(StringUtils.toInteger(member.getId()));
			
			if(dto.getAward()){
				winner.setAwardId(StringUtils.toInteger(award.getId()));
				winner.setAwardname(dto.getAwardName());
				winner.setIsAward(1);
			}else{
				winner.setAwardId(0);
				winner.setAwardname("");
				winner.setIsAward(0);
			}
			 
			Date now = new Date();
			winner.setOpenid(openId); 
			winner.setAwardOn(new Date()); 
			winner.setCreateBy(new User("0"));
			winner.setCreateDate(now);
			winner.setUpdateBy(new User("0"));
			winner.setUpdateDate(now);
			winner.setIsLimit(0); 
						
			if(sections != null && !sections.isEmpty()){
				winner.setAwardSectionCode(sections.get(0).getCode()); 
			}else{
				winner.setAwardSectionCode("0"); 
			}
			if(fromSystem != null && fromSystem.equals("mama100")){
				winner.setSource("mama100"); 
			}else{
				winner.setSource("biostime"); 
			}
			winnerService.save(winner);
			dto.setWinnerid(Integer.parseInt(winner.getId()));
			
			//扣除积分
			Map<String,String> ret2 = BiostimeWechat.Api.reduceTimes(openId);
			if(ret2==null){
				dto.setMsg("减少抽奖次数接口响应为空");
			}
			
			if(dto.getCheck()){
				String code = ret.get("code");
				if(code==null || !code.equals("100")){
					dto.setMsg(ret.get("desc"));
				}
			}
		}
		
		return dto;
	}	
	
	/**
	 * 分享页面抽奖方法
	 * @author chenweicheng
	 * @version 2016-04-28
	 */	
	@Transactional
	public DrawDto shareDraw(HttpServletRequest request){
				
		String openId = request.getParameter("openid");
		String shareId = request.getParameter("shareId");
		String gridId = request.getParameter("gridId");
		String fromSystem = request.getParameter("fromSystem");
		String registerUrl = null;
		DrawDto dto = new DrawDto();
		Winner winner = new Winner();	
		Award award = null;		
		int awardId =0;	
		Shareaward shareaward = null;
		Section sectionExm = new Section();
		sectionExm.setNow(new Date());
		List<Section> sections = sectionService.findList(sectionExm);		
		String sectionCode = null;
		if(sections != null && !sections.isEmpty()){
			sectionCode = sections.get(0).getCode();
		}
		Share share = shareService.get(shareId);
		
		//回收过期的宫格,奖品,电影兑换码
		sharegridService.recoveryGrid(shareawardService.recoveryAward());
		codeService.recoveryMovie();
		winnerService.recoveryIntimeAward();
		
		if(share == null){
			dto.setMsg("不存在该分享单！"); 
			return dto;
		}else{
			winner.setShareCode(share.getCode()); 
			Winner w = winnerService.getByCodeAndOpenid(share.getCode(), openId);
			if(w != null){
				if(!w.getSource().equals("share")){
					dto.setMsg("不好意思，你是分享者，不能抽奖！"); 
					return dto;
				}				
				else{
					dto.setMsg("不好意思，每人只能抽一次！"); 					
					return dto;
				}				
			}
		}
				
		Member member = memberService.getByOpenId(openId);
		Map<String,String> ret = BiostimeWechat.Api.getCustomerInfo(openId);
		if(ret!=null){				
			String code = ret.get("code");
			if(code==null || !code.equals("100")){
				dto.setIfMember(false); 	
			}else{
				if(member== null){			
					member = new Member();
					member.setOpenid(openId);
					member.setCustomerid(ret.get("customerId"));	
					member.setMobile(ret.get("mobile"));  
					member.setCreateBy(new User("0"));
					member.setCreateDate(new Date());
					member.setUpdateBy(new User("0"));
					member.setUpdateDate(new Date());			
					member.setNickname(ret.get("nickName"));  
					memberService.save(member);
				}
			}
		}else{
			dto.setIfMember(false); 	
		}
									
		//获取格子，如果格子还存在
		Sharegrid grid = sharegridService.get(gridId);				
		if(grid != null && grid.getIsExists().equals("0")){
			
			//随机抽取奖品
			List<HashMap<String,Object>>  awardList = shareawardService.getShareAwards(shareId);
			DistributedAwardDto drawAward = null;
			if(awardList != null && !awardList.isEmpty()){
				
				//检查电影票是否够派
				boolean checkMovie = true;
				
				//分享抽奖前检查的是伪库存，反正都≥1才能中 
				for(int i = 0;i<awardList.size();i++){		
					award = awardService.get(String.valueOf(awardId));	
					if(award != null){
						drawAward = winnerService.getSectionDrawAwards(sectionCode,String.valueOf(awardId),2);
						int awardNum = drawAward.getSum(); 
						if((award.getAmount() - awardNum < 1)){
							awardList.remove(awardList.get(i));
						}
						if(award.getAwardtype().getType().equals("moviecode")){
							if(codeService.getNotUsedMoviecode() < 1){
								checkMovie = false;
							}
						}
					}
				}					

				if(awardList.size() >0){
					if(checkMovie == true){
						dto.setAward(true);
					}else{
						dto.setMsg("抽奖失败,所配电影票不够");
						return dto;
					}
				}else{
					dto.setMsg("分享抽奖失败，伪库存已满");
					return dto;
				}
				
				Random random = new Random();
				int r = random.nextInt(awardList.size()); 
				awardId= (int) awardList.get(r).get("awardId"); 
				dto.setAwardId(String.valueOf(awardId)); 
								
				//如果抽到的不是无奖品
				if(awardId != 0){
					award = awardService.get(String.valueOf(awardId));			
					dto.setAwardName(award.getName());
					dto.setDescription(award.getDescription()); 
					dto.setAwardtypeName(award.getAwardtype().getType()); 	
					
					//如果是会员，则调用分发奖品接口（优惠券，积分）
					if(dto.getIfMember()){
					if(sendAward(award,openId) == false){
						dto.setAward(false); 
						dto.setMsg("调用积分或者优惠券接口失败"); 
						return dto;
					}
												
					}
				
				//如果抽到的是无奖品	
				}else{
					award = new Award();
					award.setId("0"); 
					dto.setAwardName("无奖品");
					shareawardService.touchAward("0",shareId);		
					sharegridService.touchGrid(gridId); 	
				}
								
				shareaward = shareawardService.getAward(award.getId(), shareId);
				if(shareaward != null){
					shareawardService.touchAward(award.getId(),shareId);					
					sharegridService.touchGrid(gridId); 						
				}
							
			}else{
				dto.setMsg("不好意思，奖品已被抽完！"); 
			}
		}else{
			dto.setMsg("不好意思，该奖品已被抽走！"); 
		}
				
		//插入中奖纪录
		if(dto.getIfMember()){
			winner.setMemberId(Integer.parseInt(member.getId()));  
		}else{
			winner.setMemberId(0);		
		}
		if(dto.getAward() && awardId != 0 ){		
			
			//如果抽到的是电影兑换码则随机抽取一张电影票
			if(award.getAwardtype().getType().equals("moviecode")){
				Moviecode mc = codeService.getAndUse();		
				if(mc != null){
					winner.setMovieCode(mc.getCode()); 
				}
			}			
			winner.setAwardId(awardId);
			winner.setAwardname(dto.getAwardName());
			winner.setIsAward(1);
			
		}else{
			winner.setAwardId(0);
			winner.setAwardname("");
			winner.setIsAward(0);
		}
		 
		Date now = new Date();
		winner.setOpenid(openId); 
		winner.setSource("share"); 
		winner.setAwardOn(new Date()); 
		winner.setCreateBy(new User("0"));
		winner.setCreateDate(now);
		winner.setUpdateBy(new User("0"));
		winner.setUpdateDate(now);	
		winner.setIsLimit(0); 
		if(sections != null && !sections.isEmpty()){
			winner.setAwardSectionCode(sectionCode); 
		}else{
			winner.setAwardSectionCode("0"); 
		}		
		if(shareaward != null){
			winner.setShareawardId(Integer.parseInt(shareaward.getId()));
			winner.setSharegridId(Integer.parseInt(gridId)); 
		}
		winnerService.save(winner);
		dto.setWinnerid(Integer.parseInt(winner.getId()));
		
		//如果是非会员则直接跳出方法
		if(!dto.getIfMember() && dto.getAward()){
			
			//生产签名
			String mySign = null;
			if(share != null){
		        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();  
		        parameters.put("shareawardId", shareaward.getId());  
		        parameters.put("shareId", shareId);
		        parameters.put("sharegridId", gridId); 
		        parameters.put("openId", openId);
		        parameters.put("datetime", share.getCreateDate().getTime());  
		        String characterEncoding = "UTF-8";  
		        mySign = SignService.createSign(characterEncoding,parameters);							
			}
					
			//获取注册回调链接
			StringBuffer url = request.getRequestURL();  
			String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();  
			String webUrl =  "http://"+Global.getConfig("serverurl")+"/f/bindAward?openId="+openId+"&shareawardId="+shareaward.getId()+"&shareId="+shareId
					+"&sharegridId="+gridId+"&fromSystem="+fromSystem+"&sign="+mySign;
			logger.info("---------"+webUrl+"---------"); 
							
			//非会员注册链接
			try {
/*				if(fromSystem != null && "mama100".equals(fromSystem)){			
					registerUrl = "http://"+BiostimeWechat.mama100Host+"/weixin/bind/auth?token="+openId+"&redirect="+URLEncoder.encode(webUrl,"utf-8");
				}
				else{
						registerUrl = "http://"+BiostimeWechat.Host+"/bncweixin/html5/register.html?url="+URLEncoder.encode(webUrl,"utf-8");
				}*/
				registerUrl = "http://"+BiostimeWechat.Host+"/bncweixin/html5/register.html?url="+URLEncoder.encode(webUrl,"utf-8");
			}catch(Exception e){
				e.printStackTrace();
			}
			dto.setRegisterUrl(registerUrl); 	
			dto.setAwardId(award.getId()); 
			logger.info("---------"+registerUrl+"---------"); 	
			
			return dto;
		}				
				
		return dto;
	}
	
	/**
	 * 新注册的会员绑定之前的中奖信息
	 * @author chenweicheng
	 * @version 2016-05-04
	 */			
	public boolean bindAward(String shareawardId,String shareId,String sharegridId,String openId,String sign){
				
		//校验签名
		Share share = shareService.get(shareId);
		String mySign = null;
		if(share != null){
	        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();  
	        parameters.put("shareawardId", shareawardId);  
	        parameters.put("shareId", shareId);
	        parameters.put("sharegridId", sharegridId); 
	        parameters.put("openId", openId);
	        parameters.put("datetime", share.getCreateDate().getTime());  
	        String characterEncoding = "UTF-8";  
	        mySign = SignService.createSign(characterEncoding,parameters);
	        if(!sign.equals(mySign)){	        	
	        	logger.info("------------绑定中奖信息失败，签名错误------------"); 
	        	return false;
	        }
		}else{
			logger.info("------------绑定中奖信息失败，不存在该分享单------------"); 
			return false;
		}
									
		//查询会员信息
		Member member = memberService.getByOpenId(openId);
		if(member==null){
			Map<String,String> ret = BiostimeWechat.Api.getCustomerInfo(openId);
			member = new Member();
			member.setOpenid(openId);
			member.setCustomerid(ret.get("customerId"));	
			member.setMobile(ret.get("mobile"));  
			member.setCreateBy(new User("0"));
			member.setCreateDate(new Date());
			member.setUpdateBy(new User("0"));
			member.setUpdateDate(new Date());			
			member.setNickname(ret.get("nickName"));  
			memberService.save(member);	
			
			//修改中奖纪录，让memberId不为0
			Winner winner = new Winner();
			winner.setMemberId(Integer.parseInt(member.getId()));
			winner.setOpenid(openId);
			winner.setShareawardId(Integer.parseInt(shareawardId)); 
			winner.setSharegridId(Integer.parseInt(sharegridId)); 
			int i = winnerService.updateWinnerMemberId(winner);
			
			if(i == 0){
				logger.info("-----------用户注册后绑定奖品信息失败,不存在该记录，或者已被人绑定----------"); 
				return false;
			}else{
				Shareaward shareAward = shareawardService.get(shareawardId);
				if(shareAward != null){
					Award award = awardService.get(String.valueOf(shareAward.getAwardId()));
					sendAward(award,openId);
				}else{
					logger.info("-----------绑定奖品信息失败,该分享单不存在该奖品----------"); 
					return false;
				}
			}
						
		}
		
		return true;
	}
	
	/**
	 * 发放奖品(积分，优惠券，电影票，实物)
	 * 其中会调用合生元提供的接口,如果调用失败就返回false
	 * @author chenweicheng
	 * @version 2016-04-28
	 */		
	public boolean sendAward(Award award,String openId){
		Map<String,String> map = null;
		String awardType = award.getAwardtype().getType();
		
		//奖品类型是积分
		if(awardType.equals("points")){
			try {
				map = BiostimeWechat.Api.modifyPoint(openId, String.valueOf((int)award.getPrice())); 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		//奖品类型是优惠券或提货券
		else if (awardType.equals("exchange") || awardType.equals("coupon")){
			if(award.getIsCoupon().equals("1") && award.getCouponId() != null){
				try {
					map =  BiostimeWechat.Api.issueCoupon(openId, award.getCouponId());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		//奖品类型是实物
		else if (awardType.equals("exchange")){
			
		}
		
		//奖品类型电影票
		else if (awardType.equals("moviecode")){
		}		
		
		if(map != null){
			if(!map.get("code").equals("coupon100") && !map.get("code").equals("100")){
				return false;
			}
		}	
		
		return true;
	}	
	
	public static int Index = 1000000000;
	
	public int randomInt(int min,int max){
		
		Random random = new Random();
		int num = random.nextInt(max);
		
		return (num % (max-min+1)) + min;
	}
	
	/**
	 * 奖品中奖范围
	 * @author chenweicheng
	 * @version 2016-04-14
	 */
	public List<AwardDto> awardRange(List<Section> sections){
		List<AwardDto> awardList = null;
		String sectionCode = sections.get(0).getCode();
		List<DistributedAwardDto> awardDtoList= winnerService.getSectionAwards(sectionCode,0);
		double rate = 0d;
		
		//获取某阶段积分奖品总数
		int sectionSum = 0;		
		int amount = 0;
		int awardId = 0;
		for (int j = 0; j < sections.size(); j++) {
			amount = sections.get(j).getAmount();
			awardId = sections.get(j).getAwardId();
			sectionSum += amount;
			if(awardDtoList != null && !awardDtoList.isEmpty()){
				for(DistributedAwardDto awardDto : awardDtoList){
					if(amount >0  && awardDto.getAwardId() ==awardId){
						if(amount >= awardDto.getSum()){
							sectionSum -= awardDto.getSum();
						}else{
							sectionSum -= Math.abs(amount - awardDto.getSum());
						}
						break;
					}
				}		
			}
		}
			
		//某奖品数量
		int sectionNum = 0;
				
		//遍历某阶段的奖品
		awardList = new ArrayList<AwardDto>();
		for (int j = 0; j < sections.size(); j++) {
			int sum = 0;
			
			AwardDto dto = new AwardDto();
			
			if(awardDtoList != null && !awardDtoList.isEmpty()){
					
				sectionNum = sections.get(j).getAmount();
				for(DistributedAwardDto awardDto : awardDtoList){
					if(awardDto.getAwardId() == sections.get(j).getAwardId()){ 
						logger.info("抽奖阶段："+awardDto.getAwardSectionCode()+"------------"+"奖品id:"+awardDto.getAwardId()+"------------"
									+"积分抽中:"+awardDto.getSum());			
						sum = awardDto.getSum();
						dto.setDistributed(sum); 
						sectionNum = sectionNum -sum;
						if(sectionNum < 0){
							sectionNum = 0;
						}
												
						break;
					}
				}
						
			}else{
				sectionNum = sections.get(j).getAmount();
			}
				
			if(sectionSum > 0){
				double   f   =   sectionNum/(double)sectionSum;  
				BigDecimal   b   =   new   BigDecimal(f);  
				double   f1   =   b.setScale(5,   BigDecimal.ROUND_HALF_UP).doubleValue();  
				rate = f1;
			}else{
				sectionSum = 0;
			}
			
			if(rate != 0){					
				dto.setId(Integer.parseInt(sections.get(j).getAward().getId())); 
				dto.setRate(rate);
				dto.setAmount(sectionNum);
				awardList.add(dto);
			}
														
		}	
		
		logger.info("---------"+"积分抽奖剩余总数："+(sectionSum)+"---------"); 
		
		//设置奖品中奖范围
		if(awardList != null && !awardList.isEmpty()){
			double r1 = 0;
			for(int i = 0;i<awardList.size();i++){
				AwardDto a = awardList.get(i);
				double r2 =a.getRate()*DrawService.Index;
				r2 = r1+r2;
				a.setStart(r1); 
				a.setEnd(r2);
				r1 = r2;
				
				logger.info("*****************************************************");		
				logger.info("---------"+"奖品编号："+a.getId()+"---------");
				logger.info("---------"+"概率："+a.getRate()+"---------");
				logger.info("---------"+"剩余数量："+a.getAmount()+"---------");
				logger.info("---------"+"开始："+a.getStart()+"---------");
				logger.info("---------"+"结束："+a.getEnd()+"---------");
				logger.info("*****************************************************");
			}			
		}		
		
		return awardList;
		
	}
	
	/**
	 * 随机抽取奖品
	 * @author chenweicheng
	 * @version 2016-04-14
	 */	
	public Award randomAward(List<AwardDto> dtoList){
		
		int r =randomInt(0,DrawService.Index+1);
		double start = 0;
		double end = 0;
		if(dtoList != null && !dtoList.isEmpty()){
			for(AwardDto dto : dtoList){
				start = dto.getStart();
				end = dto.getEnd();
										
				if(r >= start && r<end){
					Award award = awardService.get(String.valueOf(dto.getId()));		
					logger.info("随机数："+r);
					logger.info("奖品编号："+dto.getId());					
					return award;
				}
			}
		}
		
		return null;
	}

	
	/**
	 * 获取注册链接
	 * @author chenweicheng
	 * @version 2016-05-06
	 */	
	public String getRegisterUrl(HttpServletRequest request,String openId){
		
		String shareId = request.getParameter("shareId");
		String fromSystem = request.getParameter("fromSystem");
		String registerUrl = null;	
		Share share = shareService.get(shareId);
		
		
		//生产签名
		String mySign = null;
		if(share != null){
			
			Winner w = winnerService.getByCodeAndOpenid(share.getCode(), openId);
			
			if(w != null){
		        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();  
		        parameters.put("shareawardId", w.getShareawardId());  
		        parameters.put("shareId", shareId);
		        parameters.put("sharegridId", w.getSharegridId());  
		        parameters.put("openId", openId);
		        parameters.put("datetime", share.getCreateDate().getTime());  
		        String characterEncoding = "UTF-8";  
		        mySign = SignService.createSign(characterEncoding,parameters);

				//获取注册回调链接
				StringBuffer url = request.getRequestURL();  
				String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();  
				String webUrl = "http://"+Global.getConfig("serverurl")+"/f/bindAward?openId="+openId+"&shareawardId="+w.getShareawardId()+"&shareId="+shareId
						+"&sharegridId="+w.getSharegridId()+"&fromSystem="+fromSystem+"&sign="+mySign;
				logger.info("---------"+webUrl+"---------"); 
								
				//非会员注册链接
				try {
/*					if(fromSystem != null && "mama100".equals(fromSystem)){			
						registerUrl = "http://"+BiostimeWechat.mama100Host+"/weixin/bind/auth?token="+openId+"&redirect="+URLEncoder.encode(webUrl,"utf-8");
					}
					else{
							registerUrl = "http://"+BiostimeWechat.Host+"/bncweixin/html5/register.html?url="+URLEncoder.encode(webUrl,"utf-8");
					}*/					
					registerUrl = "http://"+BiostimeWechat.Host+"/bncweixin/html5/register.html?url="+URLEncoder.encode(webUrl,"utf-8");
					}	
				 catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
			}	        
		}
				
		return registerUrl;
		
	}
	
}
